package com.hmall.item.web;

import com.hmall.common.dto.PageDTO;
import com.hmall.item.constatnts.MqConstants;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.RequestParams;
import com.hmall.item.service.ItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private ItemService itemService;
    @Autowired
    RabbitTemplate rabbitTemplate;


    //减库存
    @GetMapping("/stock/{itemId}/{num}")
    public void getStock(@PathVariable Long itemId,@PathVariable Integer num) {
        Item id = itemService.getById(itemId);
        int newStock = id.getStock() - num;
        if (newStock <= 0) {
            throw new RuntimeException();
        } else {
            id.setStock(newStock);
        }
    }

    @PostMapping("/list")
    public PageDTO<Item> findAll(@RequestBody RequestParams requestParams) {
        return itemService.findAll(requestParams);
    }

    @GetMapping("/{id}")
    public Item findById(@PathVariable Long id) {
        return itemService.findById(id);
    }

    /**
     * 修改与删除请求方式不同注意区分
     *
     * @param item
     */
    @PostMapping
    public void insertItem(@RequestBody Item item) {
        itemService.insertItem(item);
    }

    @PutMapping("/status/{id}/{status}")
    public void changeStatus(@PathVariable Long id, @PathVariable Integer status) {
        itemService.changeStatus(id, status);
    }

    @PutMapping
    public void updateItem(@RequestBody Item item) {
        itemService.updateItem(item);
    }

    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable Long id) {
        itemService.removeById(id);
        rabbitTemplate.convertAndSend(MqConstants.ITEM_EXCHANGE, MqConstants.ITEM_DELETE_KEY, id);
    }
}
